# coding=utf-8

import web
from web.utils import storage

# @id 用户在猫克斯得uid
# @wbusr 通过微博接口 users/show.json 获取到得用户对象
def update_user_from_weibo_callback(id, wbusr):
    '微博回调时，更新用户'
    if wbusr:
        return web.ctx.db.update('user'
                , name = wbusr.name
                , screen_name = wbusr.screen_name
                , avatar = wbusr.profile_image_url
                , gender = wbusr.gender
                , weibo_domain = wbusr.domain
                , last_login = web.SQLLiteral('NOW()')
                , where = 'id = $id'
                , vars = locals())
    return False

# @wbusr 通过微博接口的 users/show.json 获取到得用户对象
def add_user_from_weibo_callback(wbusr):
    '微博回调时，添加用户'
    if wbusr:
        # 添加一条记录
        uid = web.ctx.db.insert('user'
                , weibo_id = wbusr.id
                , name = wbusr.name
                , screen_name = wbusr.screen_name
                , avatar = wbusr.profile_image_url
                , gender = wbusr.gender
                , weibo_domain = wbusr.domain
                , email = ''
                , date_created = web.SQLLiteral('NOW()'))
        if uid:
            # 添加成功
            return storage(id = uid, screen_name = wbusr.screen_name)
    # 添加失败
    return False

# @weibo_id 微博用户id
def get_user_by_weibo_id(weibo_id):
    '获取与指定微博绑定的用户信息'
    if not isinstance(weibo_id, long):
        # 新浪服务器返回得用户id是一个字符串类型
        # 这里转换一下
        try:
            weibo_id = long(weibo_id)
        except:
            return False

    # 读取数据库记录
    sets = web.ctx.db.select('user'
            , where = 'weibo_id = $weibo_id'
            , vars = locals())
    if sets:
        return sets[0]
    return False
